package com.zbkj.crmeb.merchant.admin.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import com.zbkj.crmeb.category.request.UpdateCateRatioRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.common.CommonPage;
import com.crmeb.core.common.CommonResult;
import com.common.PageParamRequest;
import com.crmeb.core.exception.CrmebException;
import com.utils.CrmebUtil;
import com.zbkj.crmeb.category.model.Category;
import com.zbkj.crmeb.category.request.CategoryRequest;
import com.zbkj.crmeb.category.request.CategorySearchRequest;
import com.zbkj.crmeb.category.service.CategoryService;
import com.zbkj.crmeb.category.vo.CategoryTreeVo;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.store.model.ChannelCategoryConfig;
import com.zbkj.crmeb.store.service.ChannelCategoryConfigService;
import com.zbkj.crmeb.system.service.SystemAttachmentService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 分类服务
 * @Description: 
 * @author daigb
 * @date 2021-04-16
 */
@RestController
@RequestMapping("api/admin/mer/category")
@Api(tags = "分类服务")

public class MerStoreCategoryController extends AdminBaseController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ChannelCategoryConfigService channelCategoryConfigService;
    @Autowired
    private SystemAttachmentService systemAttachmentService;

    /**
     * 分页显示分类表
     * @param request 搜索条件
     * @param pageParamRequest 分页参数
     * @author Mr.Zhang
     * @since 2020-04-16
     */
    @ApiOperation(value = "分页列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public CommonResult<CommonPage<Category>> getList(@ModelAttribute CategorySearchRequest request, @ModelAttribute PageParamRequest pageParamRequest, HttpServletRequest servletRequest) {
        return CommonResult.success(CommonPage.restPage(categoryService.getMerCateList(request,pageParamRequest,getMerId(servletRequest))));
    }

    @ApiOperation(value = "开启或关闭显示分类")
    @PutMapping("/advice")
    public CommonResult<Object> advice(@RequestBody CategoryRequest categoryRequest, HttpServletRequest servletRequest) {
        if(null == categoryRequest.getId()) {
            return CommonResult.validateFailed("ID不能为空");
        }
        if(null == categoryRequest.getIsAdvice()) {
            return CommonResult.validateFailed("类型不能为空");
        }
        int merId = getMerId(servletRequest);
        ChannelCategoryConfig merCate = channelCategoryConfigService.getOne(Wrappers.lambdaQuery(ChannelCategoryConfig.class)
                .eq(ChannelCategoryConfig::getCateId, categoryRequest.getId())
                .eq(ChannelCategoryConfig::getMerId, merId));
        boolean flag;
        if(null == merCate){
            ChannelCategoryConfig channelCategoryConfig = new ChannelCategoryConfig();
            channelCategoryConfig.setCateId(categoryRequest.getId());
            channelCategoryConfig.setIsAdvice(true);
            channelCategoryConfig.setMerId(merId);
            channelCategoryConfig.setCreateTime(new Date());
            channelCategoryConfig.setUpdateTime(new Date());
            channelCategoryConfig.setAdviceTime(new Date());
            flag = channelCategoryConfigService.save(channelCategoryConfig);
        }else {
            merCate.setIsAdvice(categoryRequest.getIsAdvice() == 1)
                    .setAdviceTime(new Date())
                    .setUpdateTime(new Date());
            flag = channelCategoryConfigService.saveOrUpdate(merCate);
        }
        return flag ? CommonResult.success() : CommonResult.failed();
    }

    /**
     * 新增分类表
     * @param categoryRequest 新增参数
     * @author Mr.Zhang
     * @since 2020-04-16
     */
    @ApiOperation(value = "新增")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public CommonResult<String> save(@Validated CategoryRequest categoryRequest) {
        Category category = new Category();

        //检测标题是否存在
        if (categoryService.checkName(categoryRequest.getName(), category.getType()) > 0) {
            throw new CrmebException("此分类已存在");
        }

        BeanUtils.copyProperties(categoryRequest, category);
        category.setPath(categoryService.getPathByPId(category.getPid()));
        category.setExtra(systemAttachmentService.clearPrefix(category.getExtra()));
        if (categoryService.save(category)) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 删除分类表
     * @param id Integer
     * @author Mr.Zhang
     * @since 2020-04-16
     */
    @ApiOperation(value = "删除")
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    @ApiImplicitParam(name = "id", value = "分类ID")
    public CommonResult<String> delete(@RequestParam(value = "id") Integer id) {
        if (categoryService.delete(id) > 0) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 修改分类表
     * @param id integer id
     * @param categoryRequest 修改参数
     * @author Mr.Zhang
     * @since 2020-04-16
     */
    @ApiOperation(value = "修改")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ApiImplicitParam(name = "id", value = "分类ID")
    public CommonResult<String> update(@RequestParam Integer id, @ModelAttribute CategoryRequest categoryRequest) {
        if (null == id || id <= 0) {
            throw new CrmebException("id 参数不合法");
        }
        categoryRequest.setExtra(systemAttachmentService.clearPrefix(categoryRequest.getExtra()));
        if (categoryService.update(categoryRequest, id)) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 查询分类表信息
     * @param id Integer
     * @author Mr.Zhang
     * @since 2020-04-16
     */
    @ApiOperation(value = "详情")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ApiImplicitParam(name = "id", value = "分类ID")
    public CommonResult<Category> info(@RequestParam(value = "id") Integer id) {
        Category category = categoryService.getById(id);
        return CommonResult.success(category);
    }

    /**
     * 查询分类表信息
     * @author Mr.Zhang
     * @since 2020-04-16
     */
    @ApiOperation(value = "获取tree结构的列表")
    @RequestMapping(value = "/list/tree", method = RequestMethod.GET)
    @ApiImplicitParams({ 
        @ApiImplicitParam(name = "type", value = "1: 产品分类，2: 附件分类，3: 文章分类， 4: 设置分类， 5: 菜单分类， 6: 配置分类， 7: 秒杀配置, 8: buyer分类 9: Europe分类 10: Tmall分类", example = "1"), 
        @ApiImplicitParam(name = "status", value = "-1=全部，0=未生效，1=已生效", example = "1") })
    public CommonResult<List<CategoryTreeVo>> getListTree(@RequestParam(name = "type") Integer type, @RequestParam(name = "status") Integer status, HttpServletRequest servletRequest) {
        return CommonResult.success(channelCategoryConfigService.getCategoryTree(getMerId(servletRequest)));
    }

    /**
     * 根据分类id集合获取分类数据
     * @param ids String id集合字符串
     * @since 2020-04-16
     */
    @ApiOperation(value = "根据id集合获取分类列表")
    @RequestMapping(value = "/list/ids", method = RequestMethod.GET)
    @ApiImplicitParam(name = "ids", value = "分类id集合")
    public CommonResult<List<Category>> getByIds(@Validated @RequestParam(name = "ids") String ids) {
        return CommonResult.success(categoryService.getByIds(CrmebUtil.stringToArray(ids)));
    }

    /**
     * 修改分类加价率
     */
    @ApiOperation(value = "修改分类加价率")
    @PostMapping(value = "/ratio/update")
    public CommonResult<Object> updateCateRatio(@RequestBody @Validated UpdateCateRatioRequest request, HttpServletRequest httpServletRequest) {
        return categoryService.updateCateRatio(request,getMerId(httpServletRequest));
    }

    @ApiOperation(value = "商户分类编辑(修改url,开启/关闭分类状态)")
    @PostMapping("/updCategory")
    public CommonResult<Object> updCategory(@RequestBody CategoryRequest categoryRequest, HttpServletRequest servletRequest) {
        if(null == categoryRequest.getId()) {
            return CommonResult.validateFailed("ID不能为空");
        }
        return channelCategoryConfigService.updChannelCategory(categoryRequest,getMerId(servletRequest)) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "获取商户小程序tree结构的列表")
    @RequestMapping(value = "/list/frontTree", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "1: 产品分类，2: 附件分类，3: 文章分类， 4: 设置分类， 5: 菜单分类， 6: 配置分类， 7: 秒杀配置, 8: buyer分类 9: Europe分类 10: Tmall分类", example = "1"),
            @ApiImplicitParam(name = "status", value = "-1=全部，0=未生效，1=已生效", example = "1") })
    public CommonResult<List<CategoryTreeVo>> getFrontTree(@RequestParam(name = "type") Integer type, @RequestParam(name = "status") Integer status, HttpServletRequest servletRequest) {
        return CommonResult.success(channelCategoryConfigService.getFrontTreeByMerId(getMerId(servletRequest)));
    }

    @ApiOperation(value = "获取商户已启用分类tree结构的列表")
    @RequestMapping(value = "/getCategoryListTree", method = RequestMethod.GET)
    public CommonResult<List<CategoryTreeVo>> getCategoryListTree(HttpServletRequest servletRequest) {
        return CommonResult.success(channelCategoryConfigService.getCategoryTree(getMerId(servletRequest)));
    }

}
